package com.rms.hkpc.util;

import com.google.gson.reflect.TypeToken;
import com.rms.hkpc.MyApplication;
import com.rms.hkpc.apiresult.ApiResultData;
import com.rms.hkpc.apiresult.LoginData;
import com.rms.hkpc.constant.AllConstants;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TokenInterceptor implements Interceptor {
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        // token已过期
        if (response.code() == 401) {
            String string = response.body().string();
            ApiResultData apiResultData = (ApiResultData) GsonUtil.getInstance().fromJson(string,
                    new TypeToken<ApiResultData>() {
                    }.getType());
            response.close();
            if (apiResultData.getStatus() == 4001) {
                MyApplication.startLogin();
                // 因为response.body().string()只能调用一次，前面已经调用过一次了，所以要重新创建新的请求
                return chain.proceed(getNewRequest(chain,SPUtil.getInstance().getString(AllConstants.TOKEN)));
            }
            String newToken = getNewToken();
            // 使用新的token，创建新的请求
            // 重新请求
            return chain.proceed(getNewRequest(chain, newToken));
        }
        return response;
    }

    private String getNewToken() {
        String newToken = "";
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", SPUtil.getInstance().getString(AllConstants.TOKEN));
            jsonObject.put("refreshToken", SPUtil.getInstance().getString(AllConstants.REFRESH_TOKEN));
            RequestBody requestBody = RequestBody.create(jsonObject.toString(), OKHttpUtil.JSON);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .readTimeout(10, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(OKHttpUtil.NET_URL + "/api/users/refreshToken")
                    .post(requestBody)
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            String result = response.body().string();
            ApiResultData<LoginData> apiResult = (ApiResultData<LoginData>) GsonUtil.getInstance().fromJson(result,
                    new TypeToken<ApiResultData<LoginData>>() {
                    }.getType());
            if (apiResult.getData() == null) {
                MyApplication.startLogin();
            } else {
                if (apiResult.getStatus() == 5500) {
                    MyApplication.startLogin();
                } else if (apiResult.getStatus() == 2000) {
                    newToken = apiResult.getData().getToken();
                    SPUtil.getInstance().putString(AllConstants.TOKEN, newToken);
                    SPUtil.getInstance().putString(AllConstants.REFRESH_TOKEN, apiResult.getData().getRefreshToken());
                }
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        return newToken;
    }

    private Request getNewRequest(Chain chain, String token) {
        return chain.request()
                .newBuilder()
                .header("Authorization","Bearer "+ token)
                .addHeader("Accept-language",LanguageUtils.getInstance().getLanguage())
                .build();
    }
}
